package org.nobject.common.apps;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class HashUtils {

	/** hexChar */
	public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	/** HASHTYPE_MD5 */
	public static String HASHTYPE_MD5="MD5"; 
	/** HASHTYPE_SHA */
	public static String HASHTYPE_SHA="SHA";
	/** HASHTYPE_SHA1 */
	public static String HASHTYPE_SHA1="SHA1"; 
	/** HASHTYPE_HMACSHA1 */
	public static String HASHTYPE_HMACSHA1="SHA-1"; 
	
	/**
	 * 获得文件的
	 * 
	 * @param filePath 文件路径
	 * @param hashType HASH类型
	 */
	public static String getHash(String filePath, String hashType) {
		InputStream fis;
		try {
			fis = new FileInputStream(filePath);
			byte[] buffer = new byte[1024];
			MessageDigest md5 = MessageDigest.getInstance(hashType);
			int numRead = 0;
			while ((numRead = fis.read(buffer)) > 0) {
				md5.update(buffer, 0, numRead);
			}
			fis.close();
			return toHexString(md5.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * toHexString
	 * 
	 * @param b
	 */
	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}

}
